<template>
  <div class="chat-left-box">
    <div class="chat-left-top">
      <div class="head-photo">
        <router-link target="_blank" :to="{path:'/userHomePage',query:{userId : currentUserInfo.userId}}">
          <img :src=currentUserInfo.userHeadPortrait width="50px" alt="">
        </router-link>
      </div>
      <div class="nickname">
        <span>{{currentUserInfo.userNickname==''?currentUserInfo.userId:currentUserInfo.userNickname}}</span>
      </div>
    </div>
    <div class="chat-left-list">
    <!-- 点击【私信TA】时，将被私信用户置顶 -->
      <div v-for="(item,index) in chatLists" :key="index">
        <router-link :to="{path:'/chat/chatContent',query:{userId:item.userId}}" >
          <!-- 选中时 -->
          <div v-if="userId == item.userId && chattedUserId == item.userId" class="list-box" :title="$t('chat.list.title')">
            <div @contextmenu.prevent="rightClick($event)"
                class="user-box"
                style="background-color: rgb(41, 41, 41);"
                @click="toChat(item.userId)">
              <div class="head-photo">
                <div v-if="item.newNewTips != '0'" class="new-counts" id="new-counts">{{item.newNewTips}}</div>
                <img :src=item.userHeadPhoto width="50px" style="border-radius: 50%;" alt="">
              </div>
              <div>
                <div class="nickname">
                  <span>{{item.userNickname==''?item.userId:item.userNickname}}</span>
                </div>
                <div class="new-news">
                  <span>{{item.latestNew}}</span>
                </div>
              </div>
              <div v-if="onlineUser.includes(item.userId)" class="online">{[$t('chat.list.online')</div>
              <div v-else class="notOnline">{{$t('chat.list.offline')}}</div>
            </div>
            <!-- 弹窗 -->
            <div class="sel-list-box">
              <div @click="deleteChatNews(item.userId,item.userNickname==''?item.userId:item.userNickname)">
                <a href="javascript:;">{{$t('chat.list.deleteChat')}}</a>
              </div>
              <div @click="cancel($event)">
                <a href="javascript:;">{{$t('chat.list.cancel')}}</a>
              </div>
            </div>
          </div>
          <!-- 未选中时 -->
          <div v-else-if="chattedUserId == item.userId" class="list-box" :title="$t('chat.list.notSelTitle')">
            <div class="user-box" @click="toChat(item.userId)">
              <div class="head-photo">
                <div v-if="item.newNewTips != '0'" class="new-counts" id="new-counts">{{item.newNewTips}}</div>
                <img :src=item.userHeadPhoto width="50px" style="border-radius: 50%;" alt="">
              </div>
              <div>
                <div class="nickname">
                  <span>{{item.userNickname==''?item.userId:item.userNickname}}</span>
                </div>
                <div class="new-news">
                  <span>{{item.latestNew}}</span>
                </div>
              </div>
              <div v-if="onlineUser.includes(item.userId)" class="online">{{$t('chat.list.online')}}</div>
              <div v-else class="notOnline">{{$t('chat.list.offline')}}</div>
            </div>
          </div>
        </router-link>
      </div>
      <div v-for="(item,index) in chatLists" :key="index">
        <router-link  :to="{path:'/chat/chatContent',query:{userId:item.userId}}">
          <!-- 选中时 -->
          <div v-if="userId == item.userId && chattedUserId != item.userId" class="list-box"  :title="$t('chat.list.title')">
            <div @contextmenu.prevent="rightClick($event)"
               class="user-box"
               style="background-color: rgb(41, 41, 41);"
               @click="toChat(item.userId)">
              <div class="head-photo">
                <div v-if="item.newNewTips != '0'" class="new-counts" id="new-counts">{{item.newNewTips}}</div>
                <img :src=item.userHeadPhoto width="50px" style="border-radius: 50%;" alt="">
              </div>
              <div>
                <div class="nickname">
                  <span>{{item.userNickname==''?item.userId:item.userNickname}}</span>
                </div>
                <div class="new-news">
                  <span>{{item.latestNew}}</span>
                </div>
              </div>
              <div v-if="onlineUser.includes(item.userId)" class="online">{{$t('chat.list.online')}}</div>
              <div v-else class="notOnline">{{$t('chat.list.offline')}}</div>
            </div>
            <!-- 弹窗 -->
            <div class="sel-list-box">
              <div @click="deleteChatNews(item.userId,item.userNickname==''?item.userId:item.userNickname)">
                <a href="javascript:;">{{$t('chat.list.deleteChat')}}</a>
              </div>
              <div @click="cancel($event)">
                <a href="javascript:;">{{$t('chat.list.cancel')}}</a>
              </div>
            </div>
          </div>
          <!-- 未选中时 -->
          <div v-else-if="chattedUserId != item.userId" class="list-box" :title="$t('chat.list.notSelTitle')">
            <div class="user-box" @click="toChat(item.userId)">
              <div class="head-photo">
                <div v-if="item.newNewTips != '0'" class="new-counts" id="new-counts">{{item.newNewTips}}</div>
                <img :src=item.userHeadPhoto width="50px" style="border-radius: 50%;" alt="">
              </div>
              <div>
                <div class="nickname">
                  <span>{{item.userNickname==''?item.userId:item.userNickname}}</span>
                </div>
                <div class="new-news">
                  <span>{{item.latestNew}}</span>
                </div>
              </div>
              <div v-if="onlineUser.includes(item.userId)" class="online">{{$t('chat.list.online')}}</div>
              <div v-else class="notOnline">{{$t('chat.list.offline')}}</div>
            </div>
          </div>
        </router-link>
      </div>
      <div v-if="chatLists.length == 0" style="width: 100%;line-height: 380px;text-align: center;color: #747474">{{$t('chat.list.noChatUser')}}</div>
    </div>
  </div>
</template>

<script>
    export default {
        name: "Chat-List",
        data(){
            return{
                userId:'',
                chatLists:'',
                onlineUser:[],

                chattedUserId:'',

                currentUserInfo:'',
                targetUserInfo:'',

                baseURL:'http://localhost:8081/user/getCurrentUserInfo',
                baseURL2:'http://localhost:8081/user/getUserInfoById/',
                baseURL3:'http://localhost:8081/cache/chatList/',
                baseURL4:'http://localhost:8081/cache/cancelNewNewsTips/',
                baseURL5:'http://localhost:8081/cache/delChatRecord/',
            }
        },
        created() {
            this.initWebSocket();
        },
        mounted(){
            this.getChatList(this.$route.query.userId);
            this.getCurrentUserInfo()
            this.getTargetUserInfo()
        },
        methods:{
            getChatList(userId){
                this.chattedUserId = userId
                this.axios.post(this.baseURL3 + userId).then(res=>{
                    this.chatLists = res.data
                    this.$forceUpdate();
                }).catch(
                    exception=>{
                        console.log(exception)
                    }
                )
            },
            setUserId(val){
                this.userId = val
            },
            setOnlineUser(arr){
                this.onlineUser = arr
            },
            getCurrentUserInfo(){
                this.axios.post(this.baseURL).then(res=>{
                    if(res.data != false){
                        this.currentUserInfo = res.data
                    }
                }).catch(
                    exception=>{
                        console.log(exception)
                    }
                )
            },
            getTargetUserInfo(){
                if (this.$route.query.userId != undefined){
                    this.axios.post(this.baseURL2 + this.$route.query.userId).then(res=>{
                        if(res.data != false){
                            this.targetUserInfo = res.data
                        }
                    }).catch(
                        exception=>{
                            console.log(exception)
                        }
                    )
                }
            },

            toChat(chattedUserId){
                document.getElementById("new-counts").style.display="none"
                this.cancelNewNewsTips(chattedUserId)
            },
            cancelNewNewsTips(chattedUserId){
                this.axios.post(this.baseURL4 + chattedUserId).then().catch(
                    exception=>{
                        console.log(exception)
                    }
                )
            },

            // 右击事件
            rightClick(e){
                e.currentTarget.nextElementSibling.style.display="block"
            },
            // 删除对话 rightClick
            deleteChatNews(userId, userNickname){
                this.$confirm(this.$t('chat.list.confirm.info'), {
                    confirmButtonText: this.$t('chat.list.confirm.confirm'),
                    cancelButtonText: this.$t('chat.list.confirm.cancel'),
                    showClose: false,
                    type: 'warning'
                }).then(() => {
                    this.axios.post(this.baseURL5 + userId).then(
                        res => {
                            this.successOpt(this.$t('chat.list.confirm.successTip'))
                            this.$router.push("/chat/chatContent")
                            this.getChatList("undefined")
                        }
                    ).catch(
                        exception => {
                            this.failOpt(this.$t('chat.list.confirm.faiTip'))
                        }
                    )

                }).catch(() => {
                    console.log(this.$t('chat.list.confirm.cancelTip'))
                });
            },
            // 取消
            cancel(e){
                e.currentTarget.parentElement.style.display="none"
            },

            initWebSocket(){ //初始化weosocket
                const socketUrl  = "ws://localhost:8081/chat";
                this.websock = new WebSocket(socketUrl);
                this.websock.onmessage = this.onMessage;
                this.websock.onopen = this.onOpen;
            },
            onMessage(evt){
                //数据接收
                // 获取服务端推送的消息
                let dataStr = evt.data
                // resObj有三个元素：isSystem、fromName、message（Str）
                let resObj = JSON.parse(dataStr)
                // 判断是否是系统消息（isSystem，为true是系统消息，false不是系统消息）
                if(resObj.system) {
                    // Set 转 Array
                    this.onlineUser = Array.from(resObj.message)
                    console.log(this.onlineUser)
                }
            },

            successOpt(message) {
                this.$notify({
                    title: this.$t('notify.success'),
                    message: message,
                    type: 'success'
                })
            },
            failOpt(message) {
                this.$notify.error({
                    title: this.$t('notify.error'),
                    message: message
                });
            }
        },
    }
</script>

<style scoped>
  .chat-left-box{
    float: left;
    width: 30%;
    height: 500px;
    background-color: rgb(73, 73, 73);
  }
  .chat-left-top{
    width: 100%;
    height: 70px;
    border-top-left-radius: 10px;
    background-color: rgb(36, 36, 36);
    border-bottom: 1.5px solid rgb(78, 78, 78);
  }
  .chat-left-top .head-photo {
    float: left;
    width: 50px;
    height: 50px;
    margin-left: 15px;
    margin-top: 12px;
    border-radius: 50%;
    overflow: hidden;
    background-color: rgb(71, 71, 71);
  }
  .chat-left-top .nickname {
    float: left;
    width: 190px;
    height: 50px;
    line-height: 50px;
    font-size: 16px;
    margin-left: 10px;
    margin-top: 12px;
    color: rgb(241, 241, 241);
    letter-spacing: 1px;
    /* 文字溢出处理 */
    display: -webkit-box;
    overflow:hidden;
    text-overflow: ellipsis;
    -webkit-box-orient:vertical;
    -webkit-line-clamp:1;
    /* background-color: white; */

  }
  .chat-left-list{
    width: 100%;
    height: 430px;
    /* background-color: rgb(32, 32, 32); */
    background-color: rgb(51, 51, 51);
    overflow: scroll;
    overflow-x: hidden;
  }
  /*滚动条样式*/
  .chat-left-list::-webkit-scrollbar {
    width: 3px;
  }
  .chat-left-list::-webkit-scrollbar-thumb {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: rgba(204, 204, 204, 0.6);
  }
  .chat-left-listody::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0);
    border-radius: 0;
    background: rgba(0,0,0,0);
  }

  .list-box{
    width:100%;
    height: 70px;
    position: relative
  }

  .user-box{
    width: 100%;
    height: 70px;
    margin-bottom: 1px;
    background-color: rgb(51, 51, 51);
    border-bottom: 1px solid rgb(34, 34, 34);
    position: relative;
  }
  .user-box .head-photo {
    float: left;
    width: 50px;
    height: 50px;
    margin-left: 15px;
    margin-top: 12px;
    border-radius: 50%;
    background-color: rgb(71, 71, 71);
    position: relative;
  }
  .new-counts {
    width: 15px;
    height: 15px;
    line-height: 15px;
    font-size: 12px;
    text-align: center;
    color: #ebeff1;
    border-radius: 50%;
    border: 1px solid rgb(233, 231, 227);
    background-color: rgb(236, 85, 58);
    position: absolute;
    top: 0px;
    right: -5px;
  }
  .user-box .nickname {
    float: left;
    width: 160px;
    height: 25px;
    line-height: 25px;
    font-size: 14px;
    margin-left: 10px;
    margin-top: 12px;
    color: rgb(241, 241, 241);
    letter-spacing: 1px;
    /* 文字溢出处理 */
    display: -webkit-box;
    overflow:hidden;
    text-overflow: ellipsis;
    -webkit-box-orient:vertical;
    -webkit-line-clamp:1;

  }
  .user-box .new-news {
    float: left;
    width: 190px;
    height: 25px;
    line-height: 25px;
    font-size: 13px;
    margin-left: 10px;
    margin-top: 0px;
    color: rgb(185, 185, 185);
    letter-spacing: 1px;
    font-weight: lighter;
    /* 文字溢出处理 */
    display: -webkit-box;
    overflow:hidden;
    text-overflow: ellipsis;
    -webkit-box-orient:vertical;
    -webkit-line-clamp:1;

  }
  .notOnline,.online{
    width: 35px;
    height: 18px;
    line-height: 18px;
    text-align: center;
    font-size: 12px;
    font-weight: lighter;
    border-radius: 3px;
    position: absolute;
    top: 12px;
    right: 10px;
  }
  .online{
    color: rgb(23, 172, 81);
    border: 1.5px solid #006a30;
    background-color: rgba(30, 128, 85, 0.2);

  }
  .notOnline{
    color: rgb(161, 58, 38);
    border: 1.5px solid #722e1e;
    background-color: rgba(255, 0, 0, 0.16);

    color: rgb(152, 151, 150);
    border: 1px solid #6a6a6b;
    background-color: rgba(255, 251, 251, 0.1);
  }
  .user-box:hover{
    background-color: rgb(41, 41, 41);
  }

  .sel-list-box{
    display: none;
    position: absolute;
    top: 50px;
    right: 10px;
    width: 80px;
    border-radius: 3px;
    background-color: rgb(246, 249, 252);
    z-index: 1;
  }
  .sel-list-box div {
    width: 100%;
    height: 23px;
    text-align: center;
    line-height: 23px;
    border-radius: 3px;
    letter-spacing: 1px;
  }
  .sel-list-box div a {
    color: #4e4e4e;
  }
  .sel-list-box div:hover {
    background-color: rgb(226, 232, 237);
  }
</style>
